import * as vscode from "vscode";
import * as fs from "fs";
import * as path from "path";

export class CacheManager {
  private static instance: CacheManager;
  private cacheFile: string;
  private cache: {
    difyApiKey?: string;
    prompts?: { [key: string]: string };
    lastUpdated?: number;
  };

  private constructor(context: vscode.ExtensionContext) {
    // 使用 context.globalStoragePath 来获取扩展的存储路径
    this.cacheFile = path.join(context.globalStoragePath, "cache.json");
    this.cache = this.loadCache();
  }

  public static getInstance(context?: vscode.ExtensionContext): CacheManager {
    if (!CacheManager.instance) {
      if (!context) {
        throw new Error("Extension context required for initialization");
      }
      CacheManager.instance = new CacheManager(context);
    }
    return CacheManager.instance;
  }

  private loadCache(): any {
    try {
      if (fs.existsSync(this.cacheFile)) {
        const data = fs.readFileSync(this.cacheFile, "utf8");
        return JSON.parse(data);
      }
    } catch (error) {
      console.error("Error loading cache:", error);
    }
    return { prompts: {} };
  }

  private saveCache(): void {
    try {
      const dirPath = path.dirname(this.cacheFile);
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
      }
      fs.writeFileSync(this.cacheFile, JSON.stringify(this.cache, null, 2));
    } catch (error) {
      console.error("Error saving cache:", error);
    }
  }

  // Dify API Key 管理
  public getDifyApiKey(): string | undefined {
    const apiKey = this.cache.difyApiKey;
    console.log(
      `[CacheManager] 读取缓存的 API Key: ${apiKey ? "已存在" : "未找到"}`
    );
    return apiKey;
  }

  public setDifyApiKey(apiKey: string): void {
    console.log(`[CacheManager] 正在缓存 API Key...`);
    this.cache.difyApiKey = apiKey;
    this.cache.lastUpdated = Date.now();
    this.saveCache();
    console.log(
      `[CacheManager] API Key 已成功缓存，更新时间: ${
        new Date(this.cache.lastUpdated).toLocaleString() + "data:" + apiKey
      }`
    );
  }

  // customPrompt 管理
  public getCustomPrompt(): string | undefined {
    const customPrompt = this.cache.prompts?.["customPrompt"];

    console.log(
      `[CacheManager] 读取缓存的 API customPrompt: ${
        customPrompt ? "已存在" : "未找到"
      }`
    );
    return this.cache.prompts?.["customPrompt"];
  }

  public setCustomPrompt(prompt: string): void {
    this.cache.prompts = { customPrompt: prompt };
    this.cache.lastUpdated = Date.now();
    console.log(
      `[CacheManager] API CustomPrompt 已成功缓存，更新时间: ${
        new Date(this.cache.lastUpdated).toLocaleString() + "data:" + prompt
      }`
    );
    this.saveCache();
  }

  // 提示词管理
  public getPrompt(key: string): string | undefined {
    return this.cache.prompts?.[key];
  }

  public setPrompt(key: string, prompt: string): void {
    if (!this.cache.prompts) {
      this.cache.prompts = {};
    }
    this.cache.prompts[key] = prompt;
    this.cache.lastUpdated = Date.now();
    this.saveCache();
  }

  public getAllPrompts(): { [key: string]: string } {
    return this.cache.prompts || {};
  }

  public clearPrompts(): void {
    this.cache.prompts = {};
    this.cache.lastUpdated = Date.now();
    this.saveCache();
  }

  public getLastUpdated(): number | undefined {
    return this.cache.lastUpdated;
  }
}
